<template>
  <div class="transaction-management">
    <div class="page-header">
      <h2>交易管理</h2>
      <div class="header-actions">
        <button @click="exportToCSV" class="btn btn-secondary">
          <span class="btn-icon">📊</span>
          导出CSV
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-box">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索卡号、交易类型..."
          class="search-input"
        />
        <button @click="searchTransactions" class="search-btn">🔍</button>
      </div>
      <div class="filter-options">
        <select v-model="typeFilter" class="filter-select">
          <option value="">全部类型</option>
          <option value="存款">存款</option>
          <option value="取款">取款</option>
          <option value="转出">转出</option>
          <option value="转入">转入</option>
        </select>
        <select v-model="dateFilter" class="filter-select">
          <option value="">全部时间</option>
          <option value="today">今天</option>
          <option value="week">本周</option>
          <option value="month">本月</option>
        </select>
      </div>
    </div>


    <!-- 交易列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>交易时间</th>
            <th>交易类型</th>
            <th>交易金额</th>
            <th>卡号</th>
            <th>备注</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="transaction in filteredTransactions" :key="transaction.id">
            <td>{{ formatDateTime(transaction.tradeDate) }}</td>
            <td>
              <span :class="['type-badge', transaction.tradeType]">
                {{ getTransactionTypeName(transaction.tradeType) }}
              </span>
            </td>
            <td :class="getAmountClass(transaction.transactionType)">
               ¥{{ transaction.tradeMoney }}
            </td>
            <td>{{ transaction.cardID }}</td>
            <td>{{ transaction.remark || '-' }}</td>
            <td>
              <div class="action-buttons">
                <button @click="viewTransactionDetails(transaction)" class="btn-icon-btn" title="查看详情">
                  👁️
                </button>
                <button @click="deleteTransaction(transaction.tradeID)" class="btn-icon-btn delete" title="删除">
                  🗑️
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 交易详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>交易详情</h3>
          <button @click="closeDetailModal" class="close-btn">✕</button>
        </div>
        <div class="modal-content">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <label>交易编号：</label>
                <span>{{ selectedTransaction?.tradeID }}</span>
              </div>
              <div class="detail-item">
                <label>交易时间：</label>
                <span>{{ formatDateTime(selectedTransaction?.tradeDate) }}</span>
              </div>
              <div class="detail-item">
                <label>交易类型：</label>
                <span>{{ getTransactionTypeName(selectedTransaction?.tradeType) }}</span>
              </div>
              <div class="detail-item">
                <label>交易金额：</label>
                <span :class="getAmountClass(selectedTransaction?.tradeType)">
                  ¥{{ selectedTransaction?.tradeMoney }}
                </span>
              </div>
              <div class="detail-item">
                <label>卡号：</label>
                <span>{{ selectedTransaction?.cardID }}</span>
              </div>
              <div class="detail-item">
                <label>备注：</label>
                <span>{{ selectedTransaction?.remark || '无' }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="closeDetailModal" class="btn btn-secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  mounted() {
    this.updateTime()
    this.refreshInterval = setInterval(this.updateTime, 1000)
  },
  name: 'TransactionManagement',
  data() {
    return {
      transactions: [],
      searchQuery: '',
      typeFilter: '',
      dateFilter: '',
      showDetailModal: false,
      selectedTransaction: null,
      formData: {
        adminID: 10011001,
        adminName: "admin",
        adminPass: "10011001"
      }
    }
  },

  computed: {

    filteredTransactions() {
      let filtered = this.transactions

      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        filtered = filtered.filter(transaction => 
          transaction.cardID.includes(query) ||
          this.getTransactionTypeName(transaction.tradeType).toLowerCase().includes(query)
        )
      }

      if (this.typeFilter) {
        filtered = filtered.filter(transaction => transaction.tradeType === this.typeFilter)
      }

      if (this.dateFilter) {
        const now = new Date()
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        const weekStart = new Date(today.getTime() - today.getDay() * 24 * 60 * 60 * 1000)
        const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)

        filtered = filtered.filter(transaction => {
          const transactionDate = new Date(transaction.tradeDate)
          switch (this.dateFilter) {
            case 'today':
              return transactionDate >= today
            case 'week':
              return transactionDate >= weekStart
            case 'month':
              return transactionDate >= monthStart
            default:
              return true
          }
        })
      }

      return filtered.sort((a, b) => new Date(b.transactionTime) - new Date(a.transactionTime))
    },
    
    totalAmount() {
      return this.filteredTransactions.reduce((sum, t) => sum + t.amount, 0).toFixed(2)
    },
    
    totalTransactions() {
      return this.filteredTransactions.length
    },
    
    todayTransactions() {
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      return this.transactions.filter(t => new Date(t.transactionTime) >= today).length
    },
    
    uniqueCards() {
      return new Set(this.filteredTransactions.map(t => t.cardNumber)).size
    }
  },
  methods: {
    deleteTransaction(transactionId) {
      const isConfirmed = confirm('确定要删除此交易记录吗？');
      if (isConfirmed) {
        // 模拟 API 请求
        this.formData.tradeID = transactionId
        console.log(this.formData)
        axios.post('http://localhost:8057/trade/delete', this.formData)
          .then((res) => {
            // 更新本地数据
            if(res.data.code === 200) {
              alert(res.data.msg);
            }else {
              alert(res.data.msg);
            }

          })
          .catch(error => {
            console.error('删除交易失败:', error);
            alert('删除交易失败，请稍后再试。');
          });
      }
    },

    async updateTime() {
      console.log(this.formData)
      try {
        const response = await axios.post('http://localhost:8057/trade/getAllTrade', this.formData);
        if (response.data.code === 200) {
          console.log(response)
          this.transactions = response.data.data; // 将返回的数据赋值给 customers
        } else {
          console.error('数据获取失败:', response.data.msg);
        }
      } catch (error) {
        console.error('接口请求失败:', error);
      }
    },
    searchTransactions() {
      // 搜索逻辑已在computed中实现
    },
    
    getTransactionTypeName(type) {
      const types = {
        deposit: '存款',
        withdraw: '取款',
        transfer: '转出',
        payment: '转入'
      }
      return types[type] || type
    },
    
    getAmountClass(type) {
      return type === 'deposit' ? 'positive' : 'negative'
    },
    
    getAmountPrefix(type) {
      return type === 'deposit' ? '+' : '-'
    },
    
    formatDateTime(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    viewTransactionDetails(transaction) {
      this.selectedTransaction = transaction
      this.showDetailModal = true
    },

    
    closeDetailModal() {
      this.showDetailModal = false
      this.selectedTransaction = null
    },
    
    exportToCSV() {
      const headers = ['交易时间', '交易类型', '交易金额', '卡号', '备注']
      const csvContent = [
        headers.join(','),
        ...this.filteredTransactions.map(transaction => [
          transaction.tradeDate,
          transaction.tradeType,
          transaction.tradeMoney,
          transaction.cardID,
          transaction.remark || ''
        ].join(','))
      ].join('\n')
      
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `交易数据_${new Date().toISOString().split('T')[0]}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      alert('交易数据导出成功！')
    }
  }
}
</script>

<style scoped>
.transaction-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn-icon {
  font-size: 16px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-box {
  display: flex;
  flex: 1;
  max-width: 400px;
}

.search-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 6px 0 0 6px;
  font-size: 14px;
}

.search-btn {
  padding: 10px 16px;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 0 6px 6px 0;
  cursor: pointer;
}

.filter-options {
  display: flex;
  gap: 12px;
}

.filter-select {
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 24px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #eff6ff;
  border-radius: 8px;
}

.stat-content h3 {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 4px 0;
  font-weight: 500;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.data-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.data-table td {
  font-size: 14px;
  color: #1f2937;
}

.type-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.type-badge.存款 {
  background: #dcfce7;
  color: #166534;
}

.type-badge.取款 {
  background: #fef2f2;
  color: #dc2626;
}

.type-badge.转出 {
  background: #dbeafe;
  color: #1d4ed8;
}

.type-badge.转入 {
  background: #fef3c7;
  color: #92400e;
}

.positive {
  color: #166534;
  font-weight: 500;
}

.negative {
  color: #dc2626;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-icon-btn {
  padding: 6px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.btn-icon-btn:hover {
  background: #f3f4f6;
}

.btn-icon-btn.delete:hover {
  background: #fef2f2;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #6b7280;
}

.modal-content {
  padding: 24px;
}

.detail-section h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 16px 0;
}

.detail-grid {
  display: grid;
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.detail-item label {
  font-weight: 500;
  color: #6b7280;
  font-size: 14px;
}

.detail-item span {
  color: #1f2937;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid #e5e7eb;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .filter-options {
    flex-direction: column;
  }
  
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 12px;
  }
  
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style> 